import './../app.scss';
import admin from './../core/admin';
import layout from './../core/layout';
import $ from 'jquery';
global.$ = global.jQuery = $;
import base from "./../../js/base/admin";
require("./../../js/jquery-distpicker/distpicker.min.js");

(function ($) {
    base($); // 插件
    layout($);
    var currentVersion = 0;

    var draftId = ($.queryString && $.queryString['draftId']) ? $.queryString['draftId'] : 0;

    if (draftId) {
        $.get(admin_draft_getById, { id: draftId }, function (res) {
            console.log(res);
            if (res.code == 200) {
                var draftType = res.data.type;
                currentVersion = res.data.version;
                var formData = res.data.content;
                if(formData){
                    var formJson = JSON.parse(formData);
                    console.log(formJson);
                    loadData(formJson);
                }
                admin($);
                $("#draft_version").val(currentVersion);
                $("#draft_type").val(draftType);
            }
            autoSave();
        });
    } else {
        $.get(admin_draft_getLatestByType, {}, function (res) {
            console.log(res);
            if (res.code == 200) {
                var draftType = res.data.type;
                currentVersion = res.data.version;
                var formData = res.data.content;
                if(formData){
                    var formJson = JSON.parse(formData);
                    console.log(formJson);
                    loadData(formJson);
                }
                admin($);
                $("#draft_version").val(currentVersion);
                $("#draft_type").val(draftType);
            }
            autoSave();
        });
    }


    $.queryString = (function (a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))

    function loadData(obj) {
        if ($.type(obj) != "object") {
            console.log("页面初始化错误！");
            return false;
        }
        var key, value, tagName, type, arr,province,city,district;
        for (var x in obj) {
            key = x;
            value = obj[x];
            $("[name='" + key + "'],[name='" + key + "[]']").each(function (index) {
                tagName = $(this)[0].tagName;
                type = $(this).attr('type');
                if (tagName == 'INPUT') {
                    if (type == 'radio') {                      //处理radio
                        $(this).attr('checked', $(this).val() == value);
                    } else if (type == 'checkbox') {             //处理checkbox
                        for (var i = 0; i < value.length; i++) {
                            if ($(this).val() == value[i]) {
                                $(this).attr('checked', true);
                                break;
                            }
                        }
                    } else if (type == 'date') {                  //处理日期型表单
                        if (parseInt(value) > 1000000000000)      //毫秒时间戳
                            $(this)[0].valueAsNumber = parseInt(value);
                        else if (parseInt(value) > 1000000000)    //秒时间戳
                            $(this)[0].valueAsNumber = parseInt(value) * 1000;
                        else                                   //字符串时间
                            $(this)[0].valueAsDate = new Date(value);
                    } else {
                        if ($.isArray(value))                    //表单组情形(多个同名表单)
                            $(this).val(value[index]);
                        else
                            $(this).val(value);
                    }
                } else if (tagName == 'SELECT') {    //处理select和textarea
                    if(key == "province"){
                        province = value;
                    }else if(key == "city"){
                        city = value;
                    }else if(key == "district"){
                        district = value;
                    }else{
                        if ($.isArray(value)){
                            $(this).val(value[index]);
                        }else{
                            $(this).val(value);
                        }
                    }
                } else if (tagName == 'TEXTAREA') {
                    $(this).text(value);
                }
            });

        }

        // console.log({
        //     province: province,
        //     city: city,
        //     district: district
        //   });

        $('#distpicker').distpicker({
            province: province,
            city: city,
            district: district
          });
        
    }

    function form2json() {
        var formData = $("form").serializeArray();
        // console.log(formData);
        var jsonData = {};
        $.each(formData, function () {
            if (jsonData[this.name]) {
                if (!jsonData[this.name].push) {
                    jsonData[this.name] = [jsonData[this.name]];
                }
                jsonData[this.name].push(this.value || '');
            } else {
                jsonData[this.name] = this.value || '';
            }
        });
        var jsonString = JSON.stringify(jsonData);
        // console.log(jsonString);
        return jsonString;
    }

    function autoSave() {
        var t = setInterval(function () {
            $("#draft_saveing").show();
            // 在这里放置要执行的代码
            var json = form2json();
            console.log(json);
            $.post(admin_draft_autoSave, { type: draftType, version: currentVersion, content: json }, function (res) {
                // console.log(res);
                currentVersion = res.data.version;
                $("#draft_saveing").hide();
            });
            // clearInterval(t);
        }, 4000);
    }

})(jQuery);
